//
//  NRWCarShopListVC.m
//  New_Runway
//
//  Created by 张记 on 2018/5/15.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarShopListVC.h"
#import "ShopModel.h"
#import "NRWCarSearchView.h"

@interface NRWCarShopListVC ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate,NRWCarSearchViewDelegate>
@property (nonatomic, strong) NSMutableArray *shopArray;
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NRWCarSearchView *searchView;
@property (nonatomic, strong) NSMutableArray *resultArray;
@end

@implementation NRWCarShopListVC
-(NSMutableArray *)resultArray{
    if (!_resultArray) {
        _resultArray = [[NSMutableArray alloc] init];
    }
    return _resultArray;
}
-(NSMutableArray *)shopArray{
    if (!_shopArray) {
        _shopArray = [[NSMutableArray alloc] init];
    }
    return _shopArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadShopList];
    [self initTableview];
    [self setupSearchBar];
}
- (void)setupSearchBar {
    
    _searchView = [[NRWCarSearchView alloc] initWithPlaceHold:@"请输入商铺名称" leftImageName:@"icon_search_vin" rightImageName:@"icon_delete_vin"];
    _searchView.delegate_custom = self;
    _searchView.delegate = self;
    self.navigationBarView.addSubview(_searchView);
    _searchView.layer.cornerRadius = 13;
    _searchView.layer.masksToBounds = YES;
    
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navigationBarView.mas_left).offset(62);
        make.right.equalTo(self.navigationBarView.mas_right).offset(-62);
        make.height.equalTo(@27);
        make.bottom.equalTo(self.navigationBarView.mas_bottom).offset(-8);
    }];
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.backgroundColor = MAIN_COLOR();
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"];
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_equalTo(self.navH);
        make.bottom.equalTo(weakSelf.view).mas_equalTo(-self.BotH);
        make.left.right.equalTo(weakSelf.view);
    }];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.resultArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
    shopResult *model = self.resultArray[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.textLabel.textColor = MAIN_FONT_COLOR();
    cell.textLabel.text = model.shopName;
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    shopResult *model = self.resultArray[indexPath.row];
    self.block(model.shopName, model.shopId);
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchView:(NRWCarSearchView *)searchView rightBtnDidClick:(UIButton *)sender {
    
     self.resultArray = [NSMutableArray arrayWithArray:self.shopArray];
     [self.tableview reloadData];
    _searchView.text = @"";
    [_searchView resignFirstResponder];

    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    [self textDidChange:text];

    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([textField.text isEqualToString:@""]) {
        
        return NO;
    }
    
    return YES;
}

-(void)textDidChange:(NSString *)searchText{
    

    [self.resultArray removeAllObjects];
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        if (searchText!=nil && searchText.length>0) {
            //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
            for (shopResult *model in self.shopArray) {
                NSString *tempStr = model.shopName;
                NSString *pinyin = [self transformToPinyin:tempStr];
                if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
                    //把搜索结果存放self.resultArray数组
                    [self.resultArray addObject:model];
                }
            }
        }else{
            self.resultArray = [NSMutableArray arrayWithArray:self.shopArray];
        }
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableview reloadData];
        });
    });
}
- (NSString *)transformToPinyin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    int count = 0;
    
    for (int  i = 0; i < pinyinArray.count; i++)
    {
        for(int i = 0; i < pinyinArray.count;i++)
        {
            if (i == count) {
                [allString appendString:@"#"];
                //区分第几个字母
            }
            [allString appendFormat:@"%@",pinyinArray[i]];
        }
        [allString appendString:@","];
        count ++;
    }
    NSMutableString *initialStr = [NSMutableString new];
    //拼音首字母
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",aString];
    return allString;
}
//商铺
-(void)loadShopList{
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,shopListApi];
    
    NSDictionary *params = @{
                             @"marketId":[NRWCarUser sharedUser].marketId,
                             @"shopState":@1
                             };
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        
        ShopModel *model = [ShopModel mj_objectWithKeyValues:response];
        if (model.code == 1) {
            for (NSDictionary *dic in model.result) {
                shopResult *model = [shopResult mj_objectWithKeyValues:dic];
                [self.shopArray addObject:model];
            }
            self.resultArray = [NSMutableArray arrayWithArray:self.shopArray];
            if (self.shopArray.count == 0) {
                [self.tableview addDefaultViewWithText:@"暂无数据!" defaultImageType:DefaultImageTypeNoData];
                
            }else{
                [self.tableview removeDefaultView];
                
            }
            [self.tableview reloadData];
        }
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
}
@end
